<template>
  <view class="goodsList">
    <u-sticky :h5NavHeight="0">
      <!-- #ifndef MP-TOUTIAO -->
      <singleHeader :pageTitle="$t('newAdmin.order.product')"></singleHeader>
      <!-- #endif -->

      <pageHeader :items="items" :index="status" @change="change"></pageHeader>
      <pageFilter
        :filter="filter"
        :BatchProcessing="BatchProcessing"
      ></pageFilter>
    </u-sticky>

    <pageGoods
      :BatchProcessing="BatchProcessing"
      :items="list"
      :statusText="getStatus(2)"
    ></pageGoods>
    <toolsMore :status="moreStatus"></toolsMore>

    <pagePopMenu ref="pagePopMenu"></pagePopMenu>

    <pagePopTextarea ref="pagePopTextarea"></pagePopTextarea>
    <pagePopAttr
      ref="pagePopAttr"
      :hoverStartTime="hoverStartTime"
      :customStyle="customStyle"
      :goodsId="goodsId"
      :status="batchStatus"
    ></pagePopAttr>
    <pagePopInp
      ref="pagePopInp"
      @changeValue="changeValue"
      :title="getTitle"
      :status="batchStatus"
    ></pagePopInp>
    <toolsGoodsShare
      ref="toolsGoodsShare"
      :shareImg="shareImg"
    ></toolsGoodsShare>

    <view class="tools-pof">
      <view class="BatchProcessing" v-if="BatchProcessing">
        <view class="let">
          <checkbox-group @change="changeAll">
            <label class="label">
              <checkbox class="checkbox" :checked="isAll" color="#fff" />
              <text>{{ $t("newAdmin.order.all") }}</text>
            </label>
          </checkbox-group>
        </view>

        <view class="rig">
          <u-button
            :customStyle="customStyle"
            :hoverStartTime="hoverStartTime"
            @click="batchUpdate('status')"
            >{{ getStatus(1) }}</u-button
          >
          <u-button
            :customStyle="customStyle"
            :hoverStartTime="hoverStartTime"
            @click="batchUpdate('remove')"
            >{{ $t("newAdmin.batchCancel") }}</u-button
          >
        </view>
      </view>
      <view class="btn" v-if="!BatchProcessing && showAdd">
        <u-button
          :customStyle="{
            background: '#F0250E',
            color: '#fff',
            borderRadius: '32px'
          }"
          :hoverStartTime="hoverStartTime"
          @click="goEdit(-1)"
          >{{ $t("title.addGood") }}</u-button
        >
      </view>
    </view>
  </view>
</template>

<script>
import singleHeader from "@/components/diySystemPage/components/singleHeader/index.vue";
import pageHeader from "./components/page-header.vue";
import pageFilter from "./components/page-filter.vue";
import pageGoods from "./components/page-goods.vue";
import pagePopMenu from "./components/page-pop-menu.vue";
import pagePopTextarea from "./components/page-pop-textarea.vue";
import pagePopAttr from "./components/page-pop-attr.vue";
import pagePopInp from "./components/page-pop-inp.vue";
import toolsMore from "@/components/tools/tools-more.vue";
import toolsGoodsShare from "@/admin/components/tools-goods-share.vue";
import {
  storeAdminGoodsList,
  storeAdminSetGoodsStatus,
  storeAdminGoodsDel,
  storeAdminSetGoodsName,
  storeAdminSetGoodsPrice
} from "@/api/admin";

export default {
  components: {
    singleHeader,
    pageHeader,
    pageFilter,
    pageGoods,
    pagePopMenu,
    pagePopTextarea,
    pagePopAttr,
    pagePopInp,
    toolsMore,
    toolsGoodsShare
  },

  data() {
    return {
      customStyle: {
        background: "#F0250E",
        color: "#fff",
        borderRadius: "32px",
        display: "inline-block",
        height: "72rpx",
        lineHeight: "72rpx",
        marginLeft: "16rpx"
      },

      hoverStartTime: 1000000,

      status: 1,
      items: [
        { name: this.$t("newAdmin.goods.up"), id: 1, num: 0 },
        { name: this.$t("admin.down"), id: 0, num: 0 }
      ],

      filter: [
        { name: this.$t("admin.creatTime"), checked: false },
        { name: this.$t("shop.shopType"), checked: false },
        { name: this.$t("shop.select"), checked: false }
      ],

      list: [],
      moreStatus: 1,
      page: 1,
      isEnd: false,

      BatchProcessing: false,
      isAll: false,

      item: null,
      batchStatus: 1, // 1.改价格 2.改库存
      shareImg: "",

      goodsId: undefined,
      showAdd: 0
    };
  },

  computed: {
    getTitle() {
      return this.batchStatus === 1
        ? this.$t("list.price")
        : this.$t("newAdmin.goods.num");
    },

    getStatus() {
      return (type) => {
        let str = "";

        if (type === 1) {
          str += this.$t("newAdmin.goods.batch");
        }

        return this.status === 1
          ? `${str + this.$t("admin.soldOut")}`
          : `${str + this.$t("admin.putOn")}`;
      };
    }
  },

  watch: {
    list: {
      handler(val) {
        if (val.every((el) => el.checked)) {
          this.isAll = true;
        } else {
          this.isAll = false;
        }
      },
      deep: true
    }
  },

  onLoad() {
    this.$utils.hideShareMenu();
  },

  onShow() {
    this.Emit.$on("filter", this.indexFilter);
    this.Emit.$on("handleGoods", this.handleGoods);
    this.Emit.$on("handleMenu", this.handleMenu);
    this.Emit.$on("changeName", this.changeName);
    this.clearData();
  },

  onHide() {
    this.Emit.$off("filter");
    this.Emit.$off("handleGoods");
    this.Emit.$off("handleMenu");
    this.Emit.$off("changeName");
  },

  methods: {
    goEdit(id) {
      let url = `/admin/goods/edit/index`;

      if (id !== -1) {
        url += `?id=${id}`;
      }

      this.$utils.toUrl(url, "navigate");
    },

    // 单个修改价格及库存
    changeValue(value) {
      let { id, batchStatus: status } = this,
        params = {
          goods_price: undefined,
          goods_num: undefined,
          id
        };

      if (status === 1) {
        params.goods_price = value;
      } else {
        params.goods_num = value;
      }

      storeAdminSetGoodsPrice(params).then((res) => {
        this.$utils.toast(res.msg);

        if (res.code === 0) {
          let $el = this.$refs.pagePopInp,
            item = this.list.find((el) => String(el.id) === String(id)),
            str = status === 1 ? "price" : "goods_num";

          this.$set(item, str, value);
          $el.showPopup = false;
          $el.disabled = false;
        }
      });
    },

    changeName(name) {
      let { item, list } = this,
        id = item.id,
        currentItem = list.find((el) => el.id === id);

      storeAdminSetGoodsName({
        id,
        name
      }).then((res) => {
        if (res.code === 0) {
          this.$set(currentItem, "name", name);
          let { pagePopTextarea } = this.$refs;
          pagePopTextarea.showPopup = false;
          pagePopTextarea.disabled = false;
          pagePopTextarea.name = "";
        }
        this.$utils.toast(res.msg);
      });
    },

    ShowModal(
      title,
      content,
      confirm = function () {},
      cancel = function () {}
    ) {
      this.$utils.showModal(
        title,
        content,
        true,
        () => {
          confirm();
        },
        () => {
          cancel();
        }
      );
    },

    handleMenu(type, name) {
      let { item, $refs } = this,
        { pagePopMenu, pagePopTextarea, toolsGoodsShare } = $refs;

      switch (type) {
        case "title":
          pagePopTextarea.name = item.name;
          pagePopTextarea.showPopup = true;
          pagePopMenu.showPopup = false;
          break;

        case "copy":
          let data = item[name];
          if (name === "goods") {
            data = `goods/goods/goods?id=${item.id}`;
          }
          uni.setClipboardData({
            data,
            success: () => {
              this.$utils.toast(this.$t("admin.copySuc"));
            }
          });
          break;

        case "share":
          this.$allrequest.goods
            .goodsQrcode({
              goods_id: item.id
            })
            .then((res) => {
              if (res.code == 0) {
                toolsGoodsShare.showPopup = true;
                toolsGoodsShare.imgshow = true;
                pagePopMenu.showPopup = false;
                this.shareImg = res.data.pic_url;
              }
            })
            .catch(() => {
              this.$u.toast(this.$t("common.posterFail"));
            });
          break;

        case "remove":
          this.storeAdminGoodsDel(item.id, () => {
            pagePopMenu.showPopup = false;
          });
          break;
      }
    },

    batchUpdate(type) {
      let ids = this.list
          .filter((el) => el.checked)
          .map((el) => el.id)
          .join(","),
        content = this.$t("newAdmin.goods.AreYouSure");

      if (!ids) {
        this.$utils.toast(this.$t("newAdmin.goods.select"));
        return;
      }

      switch (type) {
        case "status":
          this.ShowModal(this.getStatus(1), content, () => {
            let status = this.status ? 0 : 1;
            this.storeAdminSetGoodsStatus(ids, status);
          });
          break;

        case "remove":
          this.ShowModal(this.$t("newAdmin.batchCancel"), content, () => {
            this.storeAdminGoodsDel(ids);
          });
          break;
      }
    },

    handleGoods(type, item, index, status) {
      switch (type) {
        case "checked":
          this.$set(this.list[index], "checked", !this.list[index].checked);
          break;

        case "more":
          this.item = item;
          this.$refs.pagePopMenu.showPopup = true;
          break;

        case "status":
          let statusText = parseInt(item.status) === 1 ? "下架" : "上架",
            newStatus = statusText === "下架" ? "上架" : "下架";
          this.ShowModal(
            `确认${statusText}吗？`,
            `确认${statusText}该商品吗？${statusText}后可在后台编辑重新${newStatus}`,
            () => {
              let status = this.status ? 0 : 1;
              this.storeAdminSetGoodsStatus(item.id, status);
            }
          );
          break;

        case "batch":
          this.batchStatus = status;
          if (item.use_attr !== "0") {
            this.$refs.pagePopAttr.showPopup = true;
            this.goodsId = item.id;
          } else {
            this.id = item.id;
            let $el = this.$refs.pagePopInp;
            $el.showPopup = true;
            $el.value = status === 1 ? item.price : item.goods_num;
          }
          break;

        case "edit":
          this.goEdit(item.id);
          break;
      }
    },

    // 开启批量
    indexFilter() {
      this.BatchProcessing = !this.BatchProcessing;
    },

    clearData() {
      this.page = 1;
      this.isEnd = false;
      this.list = [];
      this.BatchProcessing = false;

      this.storeAdminGoodsList();
    },

    change(status) {
      this.status = status;
      this.clearData();
    },

    changeAll() {
      this.isAll = !this.isAll;
      let { list } = this;

      if (this.isAll) {
        list.forEach((el) => (el.checked = true));
      } else {
        list.forEach((el) => (el.checked = false));
      }
    },

    storeAdminSetGoodsStatus(id, status) {
      storeAdminSetGoodsStatus({
        id,
        status
      }).then((res) => {
        if (res.code === 0) {
          this.clearData();
        }

        this.$utils.toast(res.msg);
      });
    },

    storeAdminGoodsDel(id, callback) {
      storeAdminGoodsDel({
        id
      }).then((res) => {
        if (res.code === 0) {
          this.clearData();

          if (callback) {
            callback();
          }
        }

        this.$utils.toast(res.msg);
      });
    },

    storeAdminGoodsList() {
      let { list: oldList, page: pageNo, status, items } = this;

      this.moreStatus = 2;
      storeAdminGoodsList({
        pageNo,
        status,
        pageSize: 20
      })
        .then((res) => {
          uni.stopPullDownRefresh();
          this.moreStatus = 1;

          if (res.code === 0) {
            let { list, totalCount, down_status, up_status, is_add_goods } =
                res.data,
              count = parseInt(totalCount),
              downStatus = parseInt(down_status),
              upStatus = parseInt(up_status);

            this.$set(items[0], "num", upStatus);
            this.$set(items[1], "num", downStatus);

            list.forEach((el) => {
              el.checked = false;
            });

            if (list.length) {
              oldList.push(...list);
              this.page = this.page + 1;
            }

            if (oldList.length >= count) {
              this.isEnd = true;
              this.moreStatus = 3;
            }

            this.showAdd = is_add_goods;
          }
        })
        .catch(() => {
          this.moreStatus = 1;
          uni.stopPullDownRefresh();
        });
    }
  },

  onReachBottom() {
    if (this.isEnd) {
      return;
    }

    this.storeAdminGoodsList();
  },

  onPullDownRefresh() {
    this.clearData();
  }
};
</script>

<style lang="less" scoped>
.goodsList {
  position: relative;
  background: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 150rpx;
}

.title {
  height: 66rpx;
  background: #fff;
}

.box {
  height: 200vh;
}

.tools-pof {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  padding: 10rpx 30rpx calc(env(safe-area-inset-bottom) + 10rpx);
  background: #fff;
}

.BatchProcessing {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .let {
    font-size: 32rpx;
    color: #262626;
  }
}

.checkbox .wx-checkbox-input,
.checkbox .uni-checkbox-input {
  border-radius: 100rpx;
}

::v-deep {
  .uni-checkbox-input {
    border-radius: 50%;
    transform: scale(0.7);
  }

  .uni-checkbox-input-checked {
    border-color: #f0250e !important;
    background: #f0250e;
    color: #fff !important;
  }

  // #ifdef  MP-WEIXIN
  checkbox .wx-checkbox-input {
    border-radius: 50% !important;
    color: #ffffff !important;
    transform: scale(0.7);
  }

  checkbox .wx-checkbox-input.wx-checkbox-input-checked {
    color: #fff;
    background: #f0250e;
    border-color: #f0250e !important;
  }
  // #endif

  // #ifdef  MP-ALIPAY
  .checkbox {
    border: 0;
    margin-right: 20rpx;
  }

  .label {
    display: flex;
    align-items: center;
  }

  .checkbox::before {
    content: "";
    position: absolute;
    width: 40rpx;
    height: 40rpx;
    border: 1px solid #ccc;
    border-radius: 50%;
  }

  checkbox-checked::before {
    width: 40rpx;
    height: 40rpx;
    background: #f0250e;
    border: none;
  }
  // #endif
}
</style>
